package com.ming.liteflow.controller;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ming.liteflow.core.el.Flow;
import com.ming.liteflow.core.exec.ELExecUtil;
import com.ming.liteflow.core.node.NodeInfo;
import com.ming.liteflow.execption.LiteFlowELException;
import com.yomahub.liteflow.core.FlowExecutor;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.query.LambdaQuery;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/liteflow/el")
public class LiteFlowELController {

    @Resource
    private SQLManager sqlManager;

//    private Cache<String, NodeInfo> caffeineCache = Caffeine.newBuilder().initialCapacity(10).expireAfterWrite(30, TimeUnit.MINUTES).build(key -> createCache(key));
//
//    private NodeInfo createCache(String key) {
//        LambdaQuery<NodeInfo> query = sqlManager.lambdaQuery(NodeInfo.class);
//        query.andEq(NodeInfo::getId, Long.parseLong(key));
//        return query.single();
//    }

    @Resource
    private FlowExecutor flowExecutor;

    @PostMapping("/build")
    public String build(@RequestBody Map<String,Object> map) throws LiteFlowELException {
        LambdaQuery<NodeInfo> query = sqlManager.lambdaQuery(NodeInfo.class);
        List<NodeInfo> list = query.select();
        return Flow.NEW().nodeInfoList(list).logicFlow((String) map.get("json")).buildEL((Boolean) map.get("formatEL"));
    }

    @PostMapping("/exec")
    public String exec(@RequestBody Map<String,Object> map){
        return ELExecUtil.exec(flowExecutor, (String) map.get("el"));
    }
}
